package com.hong.spring.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
/**
 *
 * 功能描述: 客户端的监听器
 *
 * @param:
 * @return:
 * @auther: csh
 * @date: 2021/1/15 16:02
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {


    /**
     *
     * 功能描述: 客户端连接成功，会促发一次
     *
     * @param: 
     * @return: 
     * @auther: csh
     * @date: 2021/1/18 15:12
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello nettyServer，i'm hong!", CharsetUtil.UTF_8));
    }
    /**
     *
     * 功能描述: 接收消息方法
     *
     * @param: 
     * @return: 
     * @auther: csh
     * @date: 2021/1/18 15:12
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("server msg " + byteBuf.toString(CharsetUtil.UTF_8));
        System.out.println("server address " + ctx.channel().remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
